package com.lantosec.hmrp.core.util;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.extern.log4j.Log4j2;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 描述
 *
 * @author lichaowei
 * @date 2020/4/22
 */
@Log4j2
public class FieldUtils {


    /**
     * 根据属性名获取属性值
     */
    private static Object getFieldValueByName(String fieldName, Object o) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = o.getClass().getMethod(getter, new Class[] {});
            Object value = method.invoke(o, new Object[] {});
            return value;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取字段的值
     */
    public static String getFiledValue(Field field, Object object) {
        String result = "";
        try {
            field.setAccessible(true);
            Object value = field.get(object);
            if (!Objects.isNull(value)) {
                result = value.toString();
            }
        } catch (Exception ex) {
            log.error("获取字段的值失败。", ex);
        }
        return result;
    }

    /**
     * 设置字段的值
     */
    public static void setFiledValue(Field field, Object object, Object value) {
        try {
            field.setAccessible(true);
            field.set(object, value);
        } catch (Exception ex) {
            log.error("设置字段的值失败。", ex);
        }
    }

    /**
     * 获取Id的属性名
     */
    public static Field getIdFiled(Object o) {
        Field[] fields = o.getClass().getDeclaredFields();
        Field field = null;
        for (int i = 0; i < fields.length; i++) {
            Boolean flag = fields[i].isAnnotationPresent(TableId.class);
            if (flag) {
                TableId tableId = fields[i].getAnnotation(TableId.class);
                IdType type = tableId.type();
                if (IdType.ASSIGN_UUID.equals(type)) {
                    field = fields[i];
                }
            }
        }
        return field;
    }
}
